package com.young.interceptor;

import com.young.annotation.LoginIntercept;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler)throws Exception{
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod method=(HandlerMethod) handler;
        //判断是否有添加LoginIntercept注解
        LoginIntercept loginIntercept=method.getMethodAnnotation(LoginIntercept.class);
        if (loginIntercept==null||!loginIntercept.required()){
            //没有注解或注解的required为false，直接放行
           return true;
        }
        //鉴权
        String token = request.getHeader("token");
        if (token==null||!"token".equals(token)){
            //校验失败
            return false;
        }
        return true;
    }
}
